package chen.web.email;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;

public class DirectSender implements EmailSender{
	private static Log log = LogFactory.getLog(DirectSender.class);

	private EmailAddress senderAddress;
	public DirectSender(EmailAddress senderAddress){
		this.senderAddress = senderAddress;
	}
	
	@Override
	public boolean send(SimpleEmail email) {
		// TODO Auto-generated method stub
		try{
			EmailAddress mailTo = email.getTo();
	        String hostName = mailTo.getHostName();
	        
	        Lookup lookup = new Lookup(hostName, Type.MX);
			// 获取主机的MX记录
	        lookup.run();
	        if (lookup.getResult() != Lookup.SUCCESSFUL) {
	        	log.error("查询域名mx记录失败，地址：" + email.getTo().getAddress());
	        	return false;
	        } 
	        
	        Record[] result = lookup.getAnswers();
	        //这里只取第一个服务器
	        String host = result[0].getAdditionalName().toString(); 
	        
	        Properties prop = new Properties();
	        prop.put("mail.smtp.host", host);
	
	        Session ssn = Session.getInstance(prop, null);
	        //ssn.setDebug(true);
	        //System.setOut(new PrintStream(new File("sendlog.log")));
	        Address addressFrom = new InternetAddress(senderAddress.getAddress(), senderAddress.getUserName());
	        Address addressTo = new InternetAddress(mailTo.getAddress(), mailTo.getUserName());
	        
	        MimeBodyPart messageBodyPart = new MimeBodyPart();
	        Multipart multipart = new MimeMultipart();
	
	        messageBodyPart.setText(email.getHtml());
	        messageBodyPart.setHeader("content-type", "text/html");
	        multipart.addBodyPart(messageBodyPart);
	
	        List<File> attachments = email.getAttachments();
	        //添加附件
	        if (attachments !=null && attachments.size() > 0) { 
	            for (File attachment : attachments) {
	                messageBodyPart = new MimeBodyPart();
	                DataSource source = new FileDataSource(attachment);
	                messageBodyPart.setDataHandler(new DataHandler(source));
					String fileName = "unkown";
					try {
						//添加附件，对附件名编码
						fileName = MimeUtility.encodeWord(attachment.getName());
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						log.error("对邮件附件名编码时发生错误,附件名:" + attachment.getName(), e);
					}
	                messageBodyPart.setFileName(fileName);
	                multipart.addBodyPart(messageBodyPart);
	            }
	        }
	
	        MimeMessage message = new MimeMessage(ssn);
	
	        message.setSubject(email.getSubject());
	        message.setFrom(addressFrom);
	        message.addRecipient(Message.RecipientType.TO, addressTo);
	        message.setContent(multipart);
	        message.saveChanges();
	
	        Transport tran = (Transport) ssn.getTransport("smtp");
	        tran.connect();
	        tran.sendMessage(message, message.getAllRecipients());
	        tran.close();
		}catch(Exception ex){
			log.error("发送email出错，地址：" + email.getTo().getAddress(), ex);
			return false;
		}
		return true;
	}

}
